package com.group5.service;

import java.security.MessageDigest;
import java.util.Random;

public class Md5Util {

    private static char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};


    public static String saltGenerate()
    {
        //Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder(16);
        for(int i = 0;i<stringBuilder.capacity();i++)
        {
            stringBuilder.append(Integer.toHexString(new Random().nextInt(16)));
        }
        return stringBuilder.toString();
    }

    //带盐md5加密,返回加密结果
    public static String Md5Generate(String plaintext,String salt){
        try{
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            String plaintextwithsalt = plaintext + salt;
            String hashResult = byteArrToHex(md5.digest(plaintextwithsalt.getBytes()));
            return hashResult;
        }catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }

    //字节数组转化为十六进制字符串
    public static String byteArrToHex(byte[] btArr)
    {
        char strArr[] = new char[btArr.length *2];
        int i = 0;
        for (byte bt : btArr)
        {
            strArr[i++] = hex[bt>>>4 & 0xf];
            strArr[i++] = hex[bt & 0xf];
        }
        return new String(strArr);
    }

}

